package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ChatService;
import com.ruoyi.system.util.DataPrecess;
import com.zhishiku.filesystem.feign.ChatFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Primary
public class ChatServiceImpl implements ChatService {

    @Resource
    private ChatFeign chatFeign;

    @Value("${ai.your_api_key}")
    private String apiKey;

    @Value("${ai.chat_id}")
    private String chatId;

    @Autowired
    private RestTemplate restTemplate;

    private static final String QUICK_CHART_URL = "https://quickchart.io/chart";

    Map<String,String> Pacturetype = new LinkedHashMap<>();


    public ChatServiceImpl() {
        this.restTemplate = createRestTemplate();
        Pacturetype.put("条形","bar");
        Pacturetype.put("折线","line");
        Pacturetype.put("饼","pie");
        Pacturetype.put("雷达","radar");
        Pacturetype.put("散点","scatter");
        Pacturetype.put("柱状","bar");
        Pacturetype.put("统计","bar");
        Pacturetype.put("趋势","bar");
        Pacturetype.put("可视化","bar");
        Pacturetype.put("图表","bar");
    }

    // 配置支持二进制和JSON的转换器
    private RestTemplate createRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        // 添加二进制转换器
        restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
        // 添加JSON转换器（若需要调用/render端点）
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        return restTemplate;
    }

    @Override
    public TableDataInfo sendCompletion(Map<String, Object> request) {
        System.out.println("发送消息--------------------sendCompletion--------------------");

        //将前端控制返回方式的转换成api数据形式
        boolean isStream  = Optional.ofNullable(request.get("stream")).map(stream-> "true".equals(stream)).orElse(false);
        request.put("stream", isStream);
        Map<String, Object> resultMap = chatFeign.sendCompletion(chatId, apiKey, request);

        String answer = ((Map)resultMap.get("data")).get("answer").toString();

        if (answer.indexOf("|") < answer.lastIndexOf("|")) {
            //切割图表
            // Step 1: Find the start and end index of the table data\
            int thinkIndex = answer.indexOf("<think/>");
            int startIndex = answer.indexOf("|",thinkIndex);
            int endIndex =  answer.lastIndexOf("|") + 1;
            // Step 2: Extract the table data substring
            String tableData =  answer.substring(startIndex, endIndex).trim();

            // 先检查是否需要生成图表
            String question = (String) request.get("question");
            //if (shouldGenerateChart(question)) {
            String type;
            if ((type = getGenerateChart(question)) != null) {
                try {
                    // String input = "|日期|气温|Source|\n|------|------|------|\n|2025-03-01|27| ##0$$ |\n|2025-03-02|27| ##1$$ |\n|2025-03-03|28| ##2$$ |\n|2025-03-04|18| ##3$$ |\n|2025-03-05|16| ##4$$ |\n|2025-03-06|15| ##5$$ |\n|2025-03-07|14| ##6$$ |\n|2025-03-08|15| ##7$$ |\n|2025-03-09|19| ##8$$ |\n|2025-03-10|24| ##9$$ |\n|2025-03-11|23| ##10$$ |\n|2025-03-12|22| ##11$$ |\n|2025-03-13|21| ##12$$ |\n|2025-03-14|21| ##13$$ |"
                    Map<String, List<String>> stringListMap = DataPrecess.processData(tableData);

                    Map<String, Object> chartParams = extractChartParams(stringListMap, type);

                    return  generateChartFromData(chartParams);

                } catch (Exception e) {
                    TableDataInfo errorResult = new TableDataInfo();
                    errorResult.setCode(HttpStatus.ERROR);
                    errorResult.setMsg("图表生成失败: " + e.getMessage());
                    return errorResult;
                }
            }
        }
        //构建返回结果
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("执行成功");
        //rspData.setData(resultMap);
        return rspData;
    }
    private TableDataInfo generateChartFromData(Map<String, Object> chartParams) {
        TableDataInfo result = new TableDataInfo();
        try {
            // 调用之前实现的generateChart方法
            return generateChart(chartParams);
        } catch (Exception e) {
            result.setCode(HttpStatus.ERROR);
            result.setMsg("图表生成失败: " + e.getMessage());
            return result;
        }
    }
    private boolean shouldGenerateChart(String question) {
//        return question != null &&
//                (question.contains("图表") ||
//                        question.contains("趋势") ||
//                        question.contains("统计") ||
//                        question.contains("可视化"));
        return Pacturetype.containsKey(question);
    }

    private String getGenerateChart(String question) {

        if (question != null ){
            for (String key : Pacturetype.keySet()){
                if (question.contains(key)){
                    return Pacturetype.get(key);
                }
            }
        }
        return null;
    }

    private Map<String, Object> extractChartParams(Map<String,List<String>> paramsMap,String type) {
        // 使用传统方式初始化Map
        Map<String, Object> params = new HashMap<>();
        //params.put("type", "line");
        params.put("type", type);

        List<String> keys = paramsMap.keySet().stream().collect(Collectors.toList());
        // 构建labels列表
        //List<String> labels = Arrays.asList("Q1", "Q2", "Q3", "Q4");
        List<String> labels = paramsMap.get(keys.get(0));

        // 构建dataset
        Map<String, Object> dataset = new HashMap<>();
        dataset.put("label", keys.get(0));
        //dataset.put("data", Arrays.asList(65, 59, 80, 81));
        dataset.put("data", paramsMap.get(keys.get(1)));

        // 构建data Map
        Map<String, Object> data = new HashMap<>();
        data.put("labels", labels);
        data.put("datasets", Collections.singletonList(dataset));

        params.put("data", data);
        System.out.println("参数:"+params);
        return params;
    }

    @Override
    public TableDataInfo createSession(Map<String, Object> requestBody) {
        Long userId = SecurityUtils.getUserId();
        requestBody.put("user_id", userId.toString());
        Map<String, Object> resultMap = chatFeign.createSession(chatId, apiKey, requestBody);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("执行成功");
        rspData.setData(resultMap);
        return rspData;
    }

    @Override
    public TableDataInfo updateSession(String sessionId, Map<String, Object> requestBody) {
        Long userId = SecurityUtils.getUserId();
        requestBody.put("user_id", userId.toString());
        Map<String, Object> resultMap = chatFeign.updateSession(chatId, apiKey, sessionId, requestBody);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("执行成功");
        rspData.setData(resultMap);
        return rspData;
    }

    @Override
    public TableDataInfo getSessions(Map<String, Object> requestBody) {

        Long userId = SecurityUtils.getUserId();

        Map<String, Object> resultMap = chatFeign.getSessions(chatId, apiKey, userId.toString());

        String require = Optional.ofNullable(requestBody.get("require")).map(String::valueOf).orElse("");
        if (require.equals("list")) { //调整出简化列表
            List<Map<String, Object>> simplifiedData = new ArrayList<>();
            for (Map<String, Object> session : (List<Map<String, Object>>) resultMap.get("data")) {
                Map<String, Object> simplifiedSession = new HashMap<>();
                simplifiedSession.put("id", session.get("id"));
                simplifiedSession.put("name", session.get("name"));
                simplifiedData.add(simplifiedSession);
            }
            resultMap.put("data", simplifiedData);
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("执行成功");
        rspData.setData(resultMap);
        return rspData;
    }

    @Override
    public TableDataInfo getSession(Map<String, Object> requestBody) {

        Assert.isTrue(requestBody.containsKey("sessionId"), "sessionId不能为空");
        Long userId = SecurityUtils.getUserId();

        Map<String, Object> resultMap = chatFeign.getSession(chatId, apiKey, requestBody.get("sessionId").toString(),userId.toString());

        String require = Optional.ofNullable(requestBody.get("require")).map(String::valueOf).orElse("");
        if (require.equals("list")) { //调整出简化列表
            List<Map<String, Object>> simplifiedData = new ArrayList<>();
            for (Map<String, Object> session : (List<Map<String, Object>>) resultMap.get("data")) {
                Map<String, Object> simplifiedSession = new HashMap<>();
                simplifiedSession.put("id", session.get("id"));
                simplifiedSession.put("name", session.get("name"));
                simplifiedData.add(simplifiedSession);
            }
            resultMap.put("data", simplifiedData);
        }
        String subText = "";
        for (Map<String, Object> session : (List<Map<String, Object>>) resultMap.get("data")) {
            for (Map message : ((List<Map<String,String>>) session.get("messages"))) {
                message.put("image", "");
                message.put("Mstype","text");

                if(message.get("content").toString().contains("|")){
                    String type = "bar";
                    //确定图表类型
                    for (String key : Pacturetype.keySet()) {
                        if(subText.contains(key)){
                            type = Pacturetype.get(key);
                            break;
                        }
                    }

                    List<Map<String,String>> resultList = new ArrayList<>();
                    //切割字符串
                    String content = message.get("content").toString();
                    int think = content.indexOf("</think>");
                    int startIndex = content.indexOf("|",think);
                    int endIndex =  content.lastIndexOf("|") + 1;
                    //提取图片部分
                    String tableData =  content.substring(startIndex, endIndex).trim();
                    String preData = content.substring(0,startIndex);
                    String subData = content.substring(endIndex);

                    Map<String, List<String>> stringListMap = DataPrecess.processData(tableData);

                    Map<String, Object> chartParams = extractChartParams(stringListMap , type);
                    message.put("image", generateChartPac(chartParams));
                    message.put("Mstype","chart");
                    message.put("type","image");
                    message.put("content",preData);
                    message.put("subcontent",subData);
                }
                subText = message.get("content").toString();
            }
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("执行成功");
        rspData.setData(resultMap);
        return rspData;
    }

    @Override
    public TableDataInfo deleteSessions(Map<String, Object> requestBody) {
        //将前端string数据类型转换成id列表
        String[] ids = requestBody.get("ids").toString().split(",");
        requestBody.put("ids", ids);
        Long userId = SecurityUtils.getUserId();
        requestBody.put("user_id", userId.toString());
        //删除session
        Map<String, Object> resultMap = chatFeign.deleteSessions(chatId, apiKey, requestBody);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("执行成功");
        rspData.setData(resultMap);
        return rspData;
    }

    @Override
    public TableDataInfo generateChart(Map<String, Object> chartConfig) {
        try {
            Map<String, Object> request = new HashMap<>();
            request.put("chart", chartConfig);
            request.put("width", 600);
            request.put("height", 400);
            request.put("format", "png");
            request.put("backgroundColor", "transparent");

            ResponseEntity<byte[]> response = restTemplate.postForEntity(
                    QUICK_CHART_URL,
                    request,
                    byte[].class
            );

            if (response.getStatusCode() == org.springframework.http.HttpStatus.OK && response.hasBody()) {
                String base64Image = java.util.Base64.getEncoder().encodeToString(response.getBody());
                Map<String,String> resultMap  =  new HashMap<>();
                resultMap.put("imageData", base64Image);
                resultMap.put("Mstype","chart");
                resultMap.put("type","bot");
                return TableDataInfo.success("图表生成成功", resultMap);
            } else {
                return TableDataInfo.error("图表生成失败: 无效的API响应");
            }
        } catch (Exception e) {
            return TableDataInfo.error("图表生成失败: " + e.getMessage());
        }
    }


    public String generateChartPac(Map<String, Object> chartConfig) {
        try {
            Map<String, Object> request = new HashMap<>();
            request.put("chart", chartConfig);
            request.put("width", 600);
            request.put("height", 400);
            request.put("format", "png");
            request.put("backgroundColor", "transparent");

            ResponseEntity<byte[]> response = restTemplate.postForEntity(
                    QUICK_CHART_URL,
                    request,
                    byte[].class
            );

            if (response.getStatusCode() == org.springframework.http.HttpStatus.OK && response.hasBody()) {
                String base64Image = java.util.Base64.getEncoder().encodeToString(response.getBody());
                return base64Image;
            } else {
                return "图表生成失败: 无效的API响应";
            }
        } catch (Exception e) {
            return "图表生成失败: ";
        }
    }


}
